package com.cskaoyan.demo6.aspect;

import com.cskaoyan.demo6.annotation.Log;
import com.cskaoyan.demo6.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Component
@Aspect
public class LogAspect {
    @Autowired
    LogService logService;

    @Pointcut("@annotation(com.cskaoyan.demo6.annotation.Log)")
    public void pt(){}

    @AfterReturning(value = "pt()",returning = "result")
    public void result(JoinPoint joinPoint, Object result) throws NoSuchMethodException {
        Object target = joinPoint.getTarget();
        Class<?> targetClass = target.getClass();
        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();
        MethodSignature methodSignature = (MethodSignature) signature;
        Class<?>[] parameterTypes = methodSignature.getMethod().getParameterTypes();
        Method method = targetClass.getMethod(methodName, parameterTypes);
        Log log = method.getAnnotation(Log.class);
        String type=log.type();
        String action=log.action();
        String comment = log.comment();

        Map<String, Object> data = (Map<String, Object>) result;
        Integer code = (Integer) data.get("code");
        String msg = (String) data.get("msg");
        String status = null;

        if(code == 0){
            status = "成功";
        }else {
            status = "失败";
        }
        System.out.println(type + " " +  action + " " + comment + " " + " " + status + " " + msg + " " + methodName);
        com.cskaoyan.demo6.bean.Log log1 = new com.cskaoyan.demo6.bean.Log();
        log1.setSuccess(status);
        log1.setOperation_method(type);
        log1.setError_msg(msg);
        //构建出一个log对象，执行数据库的插入操作
        logService.addLog(log1);
    }
}
